<?php
/**
 * Hoang Nhan
 *
 ** LICENSE
 *
 * You may not change or alter any portion of this comment or credits
 * of supporting developers from this source code or any supporting source code
 * which is considered copyrighted (c) material of the original comment or credit authors.
 *
 * @copyright   2013
 * @author      Hoang Minh
 * @version     1.0
 * @since       2013/06/29
 */

/**
 * Login Controller
 * @copyright   2013
 * @author      Hoang Minh
 * @version     1.0
 * @since       2013/06/29
 */
class LoginController extends AppController  {
	public $helpers = array('Html', 'Form');
	public $uses = array('Account');
    
	/**
	 *  Action load page default layout
	 */
	public function index() {
		$this -> redirect('login');
	}
	
	/**
     * Action Login
     */
    public function login() {
    	$this -> layout = 'page_login';
    	$this -> set('title_for_layout', 'Login');
    	// Check action page postback server
    	if ($this -> request -> is('post')) {
    		$username = trim($this -> request -> data['username']);
    		
    		// Hash password input from screen
    		//$password = Security::hash($this -> request -> data['User']['password'], null, true);
    		$password = trim($this -> request ->data['password']);

			// Get subDomain from configure
    		//$dbName = Configure::read('companyDB');
    		$recordAdmin = $this -> Account -> find(
    			'first',
    			array('conditions' => array(
    				'username' => $username,
    				'password' => $password,
    				'role' => array(1,2),
    				'status' => 1
    			))
    		);
    		
    		if ($recordAdmin != array() && $this -> Auth -> login('ok')) {
	            $this -> redirect(array('controller' => 'admin', 'action' => 'index'));
			} else {
				$this -> Session -> setFlash(__('Tài khoản hoặc mật khẩu không hợp lệ.'));
			}
    	} else {
    		$this -> Session-> setFlash(__('Nhập tài khoản và mật khẩu.'));
    	}
    }

    /**
     * Action Logout
     */
    public function logout() {
    	// Check logout success
    	if ($this -> Auth -> logout()) {
    		$this -> redirect('login');
    	}
    }
}